import type { RouteLocationNormalized, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store';

export default function usePermission() {
  const userStore = useUserStore();
  return {
    accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
      const noAuth = !route.meta?.requiresAuth;
      const noRoles = !route.meta?.roles;
      const hasWildcard = route.meta?.roles?.includes('*');
      const hasUserRole = route.meta?.roles?.includes(userStore.role);

      const result = noAuth || noRoles || hasWildcard || hasUserRole;

      return result;
    },
    findFirstPermissionRoute(_routers: any, role = 'admin') {
      const cloneRouters = [..._routers];

      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift();
        const routeName = String(firstElement.name || 'unknown');

        if (
          firstElement?.meta?.roles?.find((el: string[]) => {
            const includesWildcard = Array.isArray(el) ? el.includes('*') : el === '*';
            const includesRole = Array.isArray(el) ? el.includes(role) : el === role;
            return includesWildcard || includesRole;
          })
        ) {
          return { name: firstElement.name };
        }

        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children);
        }
      }
      return null;
    }
    // You can add any rules you want
  };
}
